package com.hhw.aidlservice;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;

public class MService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("onCreate");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBind();
    }

    static class MyBind extends IAidlInterface.Stub{

        private final RemoteCallbackList<IServiceListener> list =
                new RemoteCallbackList<>();

        private final Handler handler = new Handler();
        private final Runnable heartbeat = new Runnable() {
            @Override
            public void run() {
                int size = list.beginBroadcast();
                for (int i = 0; i < size; i++) {
                    IServiceListener listener = list.getBroadcastItem(i);
                    if (listener != null) {
                        try {
                            listener.onServiceMsg("这是服务端给客户端的心跳");
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                }
                list.finishBroadcast();
                //begin和finish必须配套出现

                if (size > 0){
                    handler.postDelayed(heartbeat,1000);
                    //服务端每隔一秒发送一条数据给客户端
                }
            }
        };

        @Override
        public void onClientMsg(String msg) throws RemoteException {
            System.out.println("服务端收到客户端发送的数据:"+msg);
        }

        @Override
        public void addListener(IServiceListener listener) throws RemoteException {

            list.register(listener);

            System.out.println("服务端收到客户端的订阅监听，可以开始接收服务端发送的数据");

            handler.removeCallbacks(heartbeat);
            handler.postDelayed(heartbeat,500);//500毫秒后开始发送心跳数据
        }

        @Override
        public void removeListener(IServiceListener listener) throws RemoteException {
            list.unregister(listener);

            System.out.println("客户端取消订阅监听");
        }
    }
}
